import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Menu, Row, Col, Tree, Button, Modal, Spin, Alert } from 'antd';
import styles from './Users.css';
import moment from 'moment';
import Factory from '../factory';
import * as datetime from '../../utils/datetime'
import dataTableCreate from '../addons/DataTable'
import * as commonService from '../../services/CommonCRUD';
import * as menuService from '../../services/menus';
const daoName = "Role";
const DataTable = dataTableCreate(daoName);
const TreeNode = Tree.TreeNode;
class UserPopedom extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            isDisabled: true,
            userID: -1
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `popedom/fetchRoles`,
            payload: { daoName, permID: "1033" }
        });
        this.props.dispatch({
            type: `popedom/fetchPermTree`,
            payload: {   daoName, permID: "1033" }

        });
        this.props.dispatch({
            type: `popedom/fetchUserTree`,
            payload: {  daoName,  permID: "1033" }

        });
    }
    onSelect = (selectedKeys, info) => {
        let sel = selectedKeys[0].substring(0, 1)
        if (sel === "u") {
            let userID = Number(selectedKeys[0].substring(2, selectedKeys[0].length))
            if (userID !== undefined) {
                this.state.isDisabled = false
            }
            this.state.userID = Number(selectedKeys[0].substring(2, selectedKeys[0].length))
            this.props.dispatch({
                type: `popedom/fetchPermUserCheckedKeys`,
                payload: { userID }
            });
            this.props.dispatch({
                type: `popedom/fetchRoleTreeCheckedKeys`,
                payload: { userID }
            });
        } else {
            this.state.isDisabled = true
            const userID = -1
            this.state.userID = userID
            this.props.dispatch({
                type: `popedom/fetchPermUserCheckedKeys`,
                payload: { userID }
            });
            this.props.dispatch({
                type: `popedom/fetchRoleTreeCheckedKeys`,
                payload: { userID }
            });
        }
    }
    onPermUserTreeCheck = (permUserCheckedKeys) => {
        this.props.dispatch({
            type: `popedom/savePermUserCheckedKeys`,
            payload: { permUserCheckedKeys }
        });
    }
    onRoleTreeCheck = (roleTreeCheckedKeys) => {
        this.props.dispatch({
            type: `popedom/saveRoleTreeCheckedKeys`,
            payload: { roleTreeCheckedKeys }
        });
    }
    userSubmit() {
        let { permUserCheckedKeys, roleTreeCheckedKeys, UserTreeNodes } = this.props;
        let userID = this.state.userID
        let userkey = 'u:' + userID
        let userName = ""
        for (let i = 0; i < UserTreeNodes.length; i++) {
            if (userName === "") {
                for (let j = 0; j < UserTreeNodes[i].children.length; j++) {
                    if (UserTreeNodes[i].children[j].children !== null) {
                        for (let k = 0; k < UserTreeNodes[i].children[j].children.length; k++) {
                            if (UserTreeNodes[i].children[j].children[k].key === userkey) {
                                userName = UserTreeNodes[i].children[j].children[k].title
                                break;
                            }
                        }
                    } else {
                        if (UserTreeNodes[i].children[j].key === userkey) {
                            userName = UserTreeNodes[i].children[j].title
                            break;
                        }
                    }
                }
            } else {
                break;
            }
        }
        Modal.confirm({
            title: '提示',
            content: `你确认授予用户${userName}权限吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                menuService.userPermsSave({ userID, permUserCheckedKeys, roleTreeCheckedKeys }
                ).then(function (data) {
                    console.log(data);
                    
                    if (data === "OK") {
                        message.success("权限保存成功！")
                    }
                }.bind(this)).catch(function (ex) {
                    console.log(ex.toString())
                });
            }
        });
    }
    clearUser() {
        let { UserTreeNodes } = this.props;
        let userID = this.state.userID
        let userkey = 'u:' + userID
        let userName = ""
        for (let i = 0; i < UserTreeNodes.length; i++) {
            if (userName === "") {
                for (let j = 0; j < UserTreeNodes[i].children.length; j++) {
                    if (UserTreeNodes[i].children[j].children !== null) {
                        for (let k = 0; k < UserTreeNodes[i].children[j].children.length; k++) {
                            if (UserTreeNodes[i].children[j].children[k].key === userkey) {
                                userName = UserTreeNodes[i].children[j].children[k].title
                                break;
                            }
                        }
                    } else {
                        if (UserTreeNodes[i].children[j].key === userkey) {
                            userName = UserTreeNodes[i].children[j].title
                            break;
                        }
                    }
                }
            } else {
                break;
            }
        }
        const permUserCheckedKeys = []
        const roleTreeCheckedKeys = []
        Modal.confirm({
            title: '提示',
            content: `你确认清空用户${userName}的所有权限吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                menuService.userPermsSave({ userID, permUserCheckedKeys, roleTreeCheckedKeys }
                ).then(function (data) {
                    if (data === "OK") {
                        this.props.dispatch({
                            type: `popedom/savePermUserCheckedKeys`,
                            payload: { permUserCheckedKeys }
                        });
                        this.props.dispatch({
                            type: `popedom/saveRoleTreeCheckedKeys`,
                            payload: { roleTreeCheckedKeys }
                        });
                        message.success("权限清空成功！")
                    }
                }.bind(this)).catch(function (ex) {
                    message.error(ex.toString())
                });
            }
        });
    }
    render() {
        let { offsetHeight, roleDatas, permTreeNodes, UserTreeNodes, permUserCheckedKeys, roleTreeCheckedKeys } = this.props;
        if (roleDatas.length === 0 || permTreeNodes.length === 0 || UserTreeNodes.length === 0) {
            return (
                <Spin tip="页面加载中...">
                    <Alert
                        message="角色权限设置"
                        description="页面正在加载中，请您稍等..."
                        type="info"
                    />
                </Spin>
            )
        } else {
            const loopR = treeDatas => treeDatas.map((item) => {
                if (item.children) {
                    return (
                        <TreeNode key={item.ID} title={item.Name} >
                            {loopR(item.children)}
                        </TreeNode>
                    );
                }
                return <TreeNode key={item.ID} title={item.Name} />;
            });
            const loop = permTreeNodes => permTreeNodes.map((item) => {
                if (item.children) {
                    return (
                        <TreeNode key={item.key} title={item.title} >
                            {loop(item.children)}
                        </TreeNode>
                    );
                }
                return <TreeNode key={item.key} title={item.title} />;
            });
            const loopU = UserTreeDatas => UserTreeDatas.map((item) => {
                if (item.children) {
                    return (
                        <TreeNode key={item.key} title={item.title} >
                            {loopU(item.children)}
                        </TreeNode>
                    );
                }
                return <TreeNode key={item.key} title={item.title} />;
            });
            return (
                <div className={styles.normal} style={{ background: '#ECECEC', marginTop: -16, padding: '5px 5px' }} >
                    <Row>
                        <Col span={6} style={{ paddingRight: 15 }}>
                            <div style={{ height: offsetHeight - 100, overflow: "auto", background: "#fff" }}>
                                <Tree onSelect={this.onSelect}>
                                    {loopU(UserTreeNodes)}
                                </Tree>
                            </div>
                        </Col>
                        <Col span={9} style={{ paddingRight: 15 }}>
                            <div style={{ height: offsetHeight - 150, overflow: "auto", background: "#fff" }}>
                                <Tree
                                    checkable
                                    onCheck={this.onPermUserTreeCheck}
                                    checkedKeys={permUserCheckedKeys}
                                >
                                    {loop(permTreeNodes)}
                                </Tree>
                            </div>
                        </Col>
                        <Col span={9}>
                            <div style={{ height: offsetHeight - 150, overflow: "auto", background: "#fff" }}>
                                <Tree checkable
                                    onCheck={this.onRoleTreeCheck}
                                    checkedKeys={roleTreeCheckedKeys}
                                >
                                    {loopR(roleDatas)}
                                </Tree>
                            </div>
                        </Col>
                        <Col span={18}>
                            <div style={{ marginTop: 10 }}>
                                <Row>
                                    <Col span={12} >
                                        <span style={{ float: "right", marginRight: 10 }}>
                                            <Button type="primary" disabled={this.state.isDisabled} onClick={this.userSubmit.bind(this)}>保存</Button>
                                        </span>
                                    </Col>
                                    <Col span={12} >
                                        <span style={{ float: "left", marginLeft: 10 }}>
                                            <Button type="primary" disabled={this.state.isDisabled} onClick={this.clearUser.bind(this)}>清除</Button>
                                        </span>
                                    </Col>
                                </Row>
                            </div>
                        </Col>
                    </Row>
                </div>
            )
        }
    }
}

function mapStateToProps(state) {
    const { roleDatas, permTreeNodes, UserTreeNodes, permUserCheckedKeys, roleTreeCheckedKeys } = state.popedom;
    const { offsetHeight } = state.menus
    return {
        roleDatas,
        permTreeNodes,
        UserTreeNodes,
        offsetHeight,
        permUserCheckedKeys,
        roleTreeCheckedKeys
    }
}
UserPopedom = connect(mapStateToProps)(UserPopedom)
export default UserPopedom;

let render = (props) => React.createElement(UserPopedom, props);
let f = new Factory()
f.set("UserPopedom", render)
